package com.whl.sm.service.impl.expense;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whl.sm.common.result.Result;
import com.whl.sm.mapper.expense.TenancyBillMapper;
import com.whl.sm.model.assets.ComUnits;
import com.whl.sm.model.expense.ContractTenancy;
import com.whl.sm.model.expense.ExpenseType;
import com.whl.sm.model.expense.TenancyBill;
import com.whl.sm.model.inhabitant.AssetsTenant;
import com.whl.sm.service.assets.ComUnitsService;
import com.whl.sm.service.expense.ContractTenancyService;
import com.whl.sm.service.expense.ExpenseTypeService;
import com.whl.sm.service.expense.TenancyBillService;
import com.whl.sm.service.inhabitant.AssetsTenantService;
import com.whl.sm.service.notice.CommunityNoticeService;
import com.whl.sm.service.system.OrgUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuhaolun
 * @since 2021-10-25
 */
@Service
public class TenancyBillServiceImpl extends ServiceImpl<TenancyBillMapper, TenancyBill> implements TenancyBillService {

    @Autowired
    private AssetsTenantService assetsTenantService;

    @Autowired
    private ContractTenancyService contractTenancyService;

    @Autowired
    private ComUnitsService comUnitsService;

    @Autowired
    private ExpenseTypeService expenseTypeService;

    @Autowired
    private OrgUserService orgUserService;

    @Autowired
    private CommunityNoticeService communityNoticeService;

    @Override
    public Result update(TenancyBill tenancyBill) {
        tenancyBill.setOperator(orgUserService.getCurrentUserId());
        if (tenancyBill.getId() ==null){
            getBaseMapper().insert(tenancyBill);
        }
        else {
            getBaseMapper().updateById(tenancyBill);
        }
        return Result.ok();
    }

    @Override
    public Result addBill(TenancyBill tenancyBill) {
        try {
            String billMonth = tenancyBill.getBillMonth();
            int count = getBaseMapper().selectCount( new QueryWrapper<TenancyBill>()
                    .eq("contract_id",tenancyBill.getContractId())
                    .eq("bill_month",billMonth)
            );
            if (count > 0) {
                return Result.build(444,"账单已存在！");
            }
            ContractTenancy target = contractTenancyService.getById(tenancyBill.getContractId());
            AssetsTenant relateTenant = assetsTenantService.getById(target.getTenantId());
            ComUnits assets = comUnitsService.getById(relateTenant.getAssetsId());
            ExpenseType expenseType = expenseTypeService.getById(target.getExpenseId());
            double price = assets.getUnitArea()*expenseType.getUnitPrice()+expenseType.getDefaultPrice();
            TenancyBill insert = new TenancyBill();
            insert.setContractId(target.getId());
            insert.setUnitId(relateTenant.getAssetsId());
            insert.setBillMonth(billMonth);
            insert.setBillPrice(price);
            return this.update(insert);

        }catch (Exception e){
            e.printStackTrace();
            log.error("收费管理---->租赁合同:生成合同当月账单失败！");
            return Result.fail();
        }
    }

    @Override
    public Result payBill(String billId) {
        String userId = orgUserService.getCurrentUserId();
        TenancyBill tenancyBill = getBaseMapper().selectById(billId);
        tenancyBill.setPaymentStatus(1);
        tenancyBill.setPayer(userId);
        tenancyBill.setOperator(userId);
        tenancyBill.setPaymentTime(new Date());
        try {
            getBaseMapper().updateById(tenancyBill);
        }catch (Exception e){
            log.error("账单支付失败=======》"+e.getMessage());
            return Result.fail();
        }
        return Result.ok();
    }

    @Override
    public Result sendMessage(List<String> idList) {
        try {
            for (String item :idList){
                TenancyBill tenancyBill = getBaseMapper().selectById(item);
                ComUnits linkUnit = comUnitsService.getById(tenancyBill.getUnitId());
                List<AssetsTenant> tenants = assetsTenantService.list(new QueryWrapper<AssetsTenant>()
                        .eq("assets_id",tenancyBill.getUnitId())
                        .ne("is_del",1)
                );
                List<String> linkUsers = tenants.stream().map(AssetsTenant::getUserId).collect(Collectors.toList());
                String title = tenancyBill.getBillMonth()+"房租账单催缴";
                String noticeContent = "通知：<br>" +
                        "你好，请尽快缴纳与我方签署租赁合同的单元("+linkUnit.getUnitCode()+"),在"
                        +tenancyBill.getBillMonth()+"所需缴纳的租金,未收到款项，会认为您单方面违约，" +
                        "将解除本人的房屋代理及委托合同，同时追缴您方所欠房屋租金和滞纳金，" +
                        "由此产生的一切后果和损失由贵方自行承担。特此告知。";
                communityNoticeService.buildPersonalNotice(linkUsers,title,noticeContent);
            }
            return Result.ok();
        }catch (Exception e){
            log.error("账单催缴失败=======》"+e.getMessage());
            return Result.fail();
        }
    }
}
